package com.semp.jadoma.core.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.semp.jadoma.core.model.GalleryObject;
import com.semp.jadoma.core.util.HibernateUtil;

public class GalleryObjectDAO {
	
	private final static String FIND_BY_EXTID = "from GalleryObject o where o.externalId = :externalId";
	private final static String COUNT_BY_EXTID = "select count(*) from GalleryObject o where o.externalId = :externalId";

	public final static GalleryObject find(Long objectId) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		GalleryObject toReturn = (GalleryObject) session.get(GalleryObject.class, objectId);
		session.close();
		return toReturn;
	}
	
	public final static GalleryObject findByExternalId(Long externalId) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Query query = session.createQuery(FIND_BY_EXTID);
		query.setParameter("externalId", externalId);
		GalleryObject toReturn = (GalleryObject) query.uniqueResult();
		session.close();
		return toReturn;
	}
	
	public final static List findByExternalIdLimit(Long externalId, int offsett, int maxResults) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Query query = session.createQuery(FIND_BY_EXTID);
		query.setParameter("externalId", externalId);
		query.setFirstResult(offsett);
		query.setMaxResults(maxResults);
		List toReturn = (List) query.list();
		session.close();
		return toReturn;
	}
	
	public final static Long countByExternalId(Long externalId) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Query query = session.createQuery(COUNT_BY_EXTID);
		query.setParameter("externalId", externalId);
		Long toReturn = (Long) query.uniqueResult();
		session.close();
		return toReturn;
	}

	public final static void update(GalleryObject object) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.saveOrUpdate(object);
		session.getTransaction().commit();
		session.close();
	}

}
